package com.woniu.utils;

import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.io.InputStream;

@Component
public class UploadMinioUtil {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket}")
    private String bucketName;

    /**
     * 使用 WebFlux FilePart 上传文件到 MinIO
     */
    public Mono<String> addDocuments(FilePart filePart) {
        return filePart.content().map(dataBuffer -> {
            try (InputStream inputStream = dataBuffer.asInputStream(true)) {
                String fileName = filePart.filename();
                ObjectWriteResponse response = minioClient.putObject(PutObjectArgs.builder().stream(inputStream, dataBuffer.readableByteCount(), -1L).object(fileName).bucket(bucketName).build());
                // 获取预签名 URL
                return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(Method.GET).bucket(bucketName).object(fileName).build());
            } catch (Exception e) {
                throw new RuntimeException("文件上传失败", e);
            }
        }).next(); // 取第一个 chunk 即可
    }
}
